const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件
app.use(cors());
app.use(express.json());

// 读取JSON数据的辅助函数
function readJsonFile(filename) {
  try {
    const filePath = path.join(__dirname, 'data', filename);
    const rawData = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(rawData);
  } catch (error) {
    console.error(`Error reading ${filename}:`, error);
    return null;
  }
}

// API路由
// 获取首页数据
app.get('/api/home', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData) {
      return res.status(500).json({ error: 'Failed to load home data' });
    }
    
    res.json({
      success: true,
      data: homeData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取英雄区域数据
app.get('/api/home/hero', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData || !homeData.hero) {
      return res.status(404).json({ error: 'Hero data not found' });
    }
    
    res.json({
      success: true,
      data: homeData.hero,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取特色功能数据
app.get('/api/home/features', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData || !homeData.features) {
      return res.status(404).json({ error: 'Features data not found' });
    }
    
    res.json({
      success: true,
      data: homeData.features,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取最新文章配置数据
app.get('/api/home/latest-posts-config', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData || !homeData.latestPosts) {
      return res.status(404).json({ error: 'Latest posts config not found' });
    }
    
    res.json({
      success: true,
      data: homeData.latestPosts,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取统计数据
app.get('/api/home/stats', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData || !homeData.stats) {
      return res.status(404).json({ error: 'Stats data not found' });
    }
    
    res.json({
      success: true,
      data: homeData.stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取个人信息数据
app.get('/api/home/personal-info', (req, res) => {
  try {
    const homeData = readJsonFile('homeData.json');
    if (!homeData || !homeData.personalInfo) {
      return res.status(404).json({ error: 'Personal info not found' });
    }
    
    res.json({
      success: true,
      data: homeData.personalInfo,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// ================== 博客相关API ==================

// 获取完整博客数据
app.get('/api/blog', (req, res) => {
  try {
    const blogData = readJsonFile('blogData.json');
    if (!blogData) {
      return res.status(500).json({ error: 'Failed to load blog data' });
    }
    
    res.json({
      success: true,
      data: blogData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取所有博客文章
app.get('/api/blog/posts', (req, res) => {
  try {
    const blogData = readJsonFile('blogData.json');
    if (!blogData || !blogData.posts) {
      return res.status(404).json({ error: 'Blog posts not found' });
    }
    
    // 支持查询参数
    const { category, tag, search, sort, limit, offset } = req.query;
    let posts = [...blogData.posts];
    
    // 分类筛选
    if (category && category !== '') {
      posts = posts.filter(post => post.category === category);
    }
    
    // 标签筛选
    if (tag) {
      posts = posts.filter(post => post.tags.includes(tag));
    }
    
    // 搜索
    if (search) {
      const searchTerm = search.toLowerCase();
      posts = posts.filter(post => 
        post.title.toLowerCase().includes(searchTerm) ||
        post.excerpt.toLowerCase().includes(searchTerm) ||
        post.tags.some(t => t.toLowerCase().includes(searchTerm))
      );
    }
    
    // 排序
    switch (sort) {
      case 'date':
        posts.sort((a, b) => new Date(b.date) - new Date(a.date));
        break;
      case 'views':
        posts.sort((a, b) => b.views - a.views);
        break;
      case 'title':
        posts.sort((a, b) => a.title.localeCompare(b.title));
        break;
      default:
        posts.sort((a, b) => new Date(b.date) - new Date(a.date));
    }
    
    // 分页
    const total = posts.length;
    if (offset || limit) {
      const start = parseInt(offset) || 0;
      const count = parseInt(limit) || posts.length;
      posts = posts.slice(start, start + count);
    }
    
    res.json({
      success: true,
      data: {
        posts,
        pagination: {
          total,
          offset: parseInt(offset) || 0,
          limit: parseInt(limit) || total,
          hasMore: (parseInt(offset) || 0) + (parseInt(limit) || total) < total
        }
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 根据ID获取单篇文章
app.get('/api/blog/posts/:id', (req, res) => {
  try {
    const blogData = readJsonFile('blogData.json');
    if (!blogData || !blogData.posts) {
      return res.status(404).json({ error: 'Blog posts not found' });
    }
    
    const postId = parseInt(req.params.id);
    const post = blogData.posts.find(p => p.id === postId);
    
    if (!post) {
      return res.status(404).json({ error: 'Post not found' });
    }
    
    // 获取相关文章（相同分类或标签）
    const relatedPosts = blogData.posts
      .filter(p => p.id !== postId)
      .filter(p => 
        p.category === post.category || 
        p.tags.some(tag => post.tags.includes(tag))
      )
      .sort((a, b) => new Date(b.date) - new Date(a.date))
      .slice(0, 3);
    
    res.json({
      success: true,
      data: {
        post,
        relatedPosts
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取博客页面配置
app.get('/api/blog/config', (req, res) => {
  try {
    const blogData = readJsonFile('blogData.json');
    if (!blogData) {
      return res.status(500).json({ error: 'Failed to load blog data' });
    }
    
    res.json({
      success: true,
      data: {
        pageInfo: blogData.pageInfo,
        categories: blogData.categories,
        sortOptions: blogData.sortOptions,
        stats: blogData.stats
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取博客统计数据
app.get('/api/blog/stats', (req, res) => {
  try {
    const blogData = readJsonFile('blogData.json');
    if (!blogData || !blogData.stats) {
      return res.status(404).json({ error: 'Blog stats not found' });
    }
    
    res.json({
      success: true,
      data: blogData.stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// ================== 关于我页面相关API ==================

// 获取完整关于我页面数据
app.get('/api/about', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData) {
      return res.status(500).json({ error: 'Failed to load about data' });
    }
    
    res.json({
      success: true,
      data: aboutData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取个人信息和统计数据
app.get('/api/about/personal-info', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.personalInfo) {
      return res.status(404).json({ error: 'Personal info not found' });
    }
    
    res.json({
      success: true,
      data: aboutData.personalInfo,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取技能和专长数据
app.get('/api/about/skills', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.skills) {
      return res.status(404).json({ error: 'Skills data not found' });
    }
    
    // 支持按技能类型筛选
    const { category } = req.query;
    let skills = aboutData.skills;
    
    if (category) {
      skills = skills.filter(skill => skill.id === category);
    }
    
    res.json({
      success: true,
      data: {
        skills,
        categories: aboutData.skills.map(skill => ({
          id: skill.id,
          title: skill.title,
          color: skill.color
        }))
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取学习历程
app.get('/api/about/learning-journey', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.learningJourney) {
      return res.status(404).json({ error: 'Learning journey not found' });
    }
    
    res.json({
      success: true,
      data: aboutData.learningJourney,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取兴趣爱好
app.get('/api/about/interests', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.interests) {
      return res.status(404).json({ error: 'Interests not found' });
    }
    
    res.json({
      success: true,
      data: aboutData.interests,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取个人项目
app.get('/api/about/projects', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.projects) {
      return res.status(404).json({ error: 'Projects not found' });
    }
    
    // 支持按状态筛选项目
    const { status } = req.query;
    let projects = aboutData.projects;
    
    if (status) {
      projects = projects.filter(project => project.status === status);
    }
    
    res.json({
      success: true,
      data: {
        projects,
        statuses: [...new Set(aboutData.projects.map(p => p.status))]
      },
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 根据ID获取单个项目详情
app.get('/api/about/projects/:id', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.projects) {
      return res.status(404).json({ error: 'Projects not found' });
    }
    
    const projectId = req.params.id;
    const project = aboutData.projects.find(p => p.id === projectId);
    
    if (!project) {
      return res.status(404).json({ error: 'Project not found' });
    }
    
    res.json({
      success: true,
      data: project,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取教育背景
app.get('/api/about/education', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.education) {
      return res.status(404).json({ error: 'Education data not found' });
    }
    
    res.json({
      success: true,
      data: aboutData.education,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取联系方式
app.get('/api/about/contact', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.contact) {
      return res.status(404).json({ error: 'Contact info not found' });
    }
    
    res.json({
      success: true,
      data: aboutData.contact,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 获取技能统计信息
app.get('/api/about/skills/stats', (req, res) => {
  try {
    const aboutData = readJsonFile('aboutData.json');
    if (!aboutData || !aboutData.skills) {
      return res.status(404).json({ error: 'Skills data not found' });
    }
    
    const stats = {
      totalSkills: aboutData.skills.length,
      totalTechnologies: aboutData.skills.reduce((total, skill) => total + skill.technologies.length, 0),
      averageLevel: Math.round(
        aboutData.skills.reduce((total, skill) => 
          total + skill.technologies.reduce((sum, tech) => sum + tech.level, 0) / skill.technologies.length, 0
        ) / aboutData.skills.length
      ),
      topSkills: aboutData.skills
        .flatMap(skill => skill.technologies)
        .sort((a, b) => b.level - a.level)
        .slice(0, 5)
        .map(tech => ({ name: tech.name, level: tech.level }))
    };
    
    res.json({
      success: true,
      data: stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: 'Internal server error',
      message: error.message 
    });
  }
});

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'Blog API Server is running',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: 'Blog API Server',
    version: '1.0.0',
    endpoints: [
      'GET /api/health - 健康检查',
      '==== 首页相关API ====',
      'GET /api/home - 获取完整首页数据', 
      'GET /api/home/hero - 获取英雄区域数据',
      'GET /api/home/features - 获取特色功能数据',
      'GET /api/home/latest-posts-config - 获取最新文章配置',
      'GET /api/home/stats - 获取统计数据',
      'GET /api/home/personal-info - 获取个人信息',
      '==== 博客相关API ====',
      'GET /api/blog - 获取完整博客数据',
      'GET /api/blog/posts - 获取所有博客文章(支持筛选、搜索、分页)',
      'GET /api/blog/posts/:id - 获取单篇文章和相关文章',
      'GET /api/blog/config - 获取博客页面配置',
      'GET /api/blog/stats - 获取博客统计数据',
      '==== 关于我页面相关API ====',
      'GET /api/about - 获取完整关于我页面数据',
      'GET /api/about/personal-info - 获取个人信息和统计数据',
      'GET /api/about/skills - 获取技能和专长数据(支持分类筛选)',
      'GET /api/about/skills/stats - 获取技能统计信息',
      'GET /api/about/learning-journey - 获取学习历程',
      'GET /api/about/interests - 获取兴趣爱好',
      'GET /api/about/projects - 获取个人项目(支持状态筛选)',
      'GET /api/about/projects/:id - 获取单个项目详情',
      'GET /api/about/education - 获取教育背景',
      'GET /api/about/contact - 获取联系方式'
    ]
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    error: 'API endpoint not found',
    path: req.originalUrl
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('Error:', error);
  res.status(500).json({
    success: false,
    error: 'Internal server error',
    message: process.env.NODE_ENV === 'development' ? error.message : 'Something went wrong'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 Blog API Server is running on http://localhost:${PORT}`);
  console.log(`📊 Health check: http://localhost:${PORT}/api/health`);
  console.log(`🏠 Home data API: http://localhost:${PORT}/api/home`);
});

module.exports = app;
